const joi = require('joi');
const dbQuery = require('../model/db');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 验证规则
// name create_time
const schemaAddMusicType = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	create_time: joi.string().required().error(new Error('create_time不符合验证规则')),
})

// id name(new)
const schemaEditMusicType = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaDeleteMusicTypeAndGet = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaDeleteMusicAndGet = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

// name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
const schemaAddMusic = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	musictypeId: joi.number().required().error(new Error('musictypeId不符合验证规则')),
	singerId: joi.number().required().error(new Error('singerId不符合验证规则')),
})

const schemaGetMusicById = joi.object({
	id: joi.string().required().error(new Error('id不符合验证规则'))
})

const schemaEditMusic = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	musictypeId: joi.number().required().error(new Error('musictypeId不符合验证规则')),
	singerId: joi.number().required().error(new Error('singerId不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则')),
})

// name create_time
const addMusicType = async function (req, res, next) {
	let {
		name,
		create_time
	} = req.body;

	if (!name || !create_time) {
		sendError(res, 200, '类型名称或创建时间不能为空!');
		return;
	}

	try {
		await schemaAddMusicType.validateAsync({
			name,
			create_time
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from musictype where musictype_name=?'
	let result = await dbQuery(sqlStr, name);
	if (result.length !== 0) {
		sendError(res, 200, '类型名称被占用，请更换其他类型名称!');
		return;
	}

	let sqlStr1 = 'insert into musictype (musictype_name,musictype_create_time) values (?,?)';
	let result1 = await dbQuery(sqlStr1, [name, create_time]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加musictype成功!');
	} else {
		sendError(res, 500, '添加音乐类型失败，请稍后再试!')
	}
}

// id name(new)
const editMusicType = async function (req, res, next) {
	let {
		id,
		name
	} = req.body;

	if (!name || !id) {
		sendError(res, 200, '类型名称或id不能为空!');
		return;
	}

	try {
		await schemaEditMusicType.validateAsync({
			name,
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from musictype where musictype_name=? and musictypeid!=?'
	let result = await dbQuery(sqlStr, [name, id]);
	if (result.length !== 0) {
		sendError(res, 200, '类型名称已被占用，请更换后重试!');
		return;
	}

	let sqlStr1 = 'update musictype set musictype_name=? where musictypeid=?'
	let result1 = await dbQuery(sqlStr1, [name, id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '修改音乐类型成功!');
	} else {
		sendError(res, 500, '修改音乐类型失败，请稍后再试!')
	}
}

// id
const deleteMusicType = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteMusicTypeAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	// 如果music中有该musictype,就不能删除
	let sqlStr = 'select * from music where musictype_id=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length !== 0) {
		sendError(res, 200, '删除音乐类型失败，该音乐类型有对应的音乐!')
		return;
	}

	// 删除
	let sqlStr1 = 'delete from musictype where musictypeid=?';
	let result1 = await dbQuery(sqlStr1, [id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '删除音乐类型成功!');
	} else {
		sendError(res, 500, '删除音乐类型失败，请稍后再试!')
	}
}

const getMusicType = async function (req, res, next) {
	let sqlStr = 'select * from musictype';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取音乐类型成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取音乐类型失败，请稍后再试!')
	}
}

// id
const getMusicTypeById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！');
		return;
	}

	try {
		await schemaDeleteMusicTypeAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from musictype where musictypeid=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length >= 0) {
		sendSuccess(res, '获取音乐类型成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取音乐类型失败，请稍后再试!')
	}
}

// name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
const addMusic = async function (req, res, next) {
	let info = req.body;

	if (!info.name || !info.musictypeId || !info.singerId) {
		sendError(res, 200, '音乐名称或音乐类型或歌手不能为空!');
		return;
	}

	if (!req.files["picfile"]) {
		sendError(res, 200, '图片不能为空！')
		return;
	}

	if (!info.musicurl && !req.files["musicfile"]) {
		sendError(res, 200, '音乐地址或音乐文件不能为空！');
		return;
	}

	try {
		await schemaAddMusic.validateAsync({
			name: info.name,
			musictypeId: info.musictypeId,
			singerId: info.singerId
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from music where music_name=?';
	let result = await dbQuery(sqlStr, info.name);
	if (result.length !== 0) {
		sendError(res, 200, '音乐名称被占用，请更换其他音乐名称!');
		return;
	}

	if (!info.musicurl) {
		var file = req.files["musicfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/')
	} else {
		var musicurl = info.musicurl;
	}

	var img = req.files["picfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
	let sqlStr1 = 'insert into music (music_name,musictype_id,music_url,music_file,music_pic_url,singer_id) values (?,?,?,?,?,?)';
	let result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, musicurl, file, img, info.singerId]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加音乐成功!');
	} else {
		sendError(res, 500, '添加音乐失败，请稍后再试!')
	}
}

// id
const deleteMusic = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteMusicAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let reslut4 = await dbQuery('select * from music where musicid=?', [id]);
	if (reslut4.length == 0) {
		sendError(res, 200, '删除音乐失败，已删除该音乐！');
		return;
	}

	// 级联删除
	let sqlStr = 'delete from music where musicid=?';
	let result = await dbQuery(sqlStr, [id]);
	let sqlStr1 = 'delete from collect where music_id=?';
	let result1 = await dbQuery(sqlStr1, [id]);
	let sqlStr2 = 'delete from comment where music_id=?';
	let result2 = await dbQuery(sqlStr2, [id]);
	// 删除歌单中有该音乐id
	let sqlStr3 = "select * from gedan";
	let result3 = await dbQuery(sqlStr3, [id]);
	var narr = [];
	for (var i = 0; i < result3.length; i++) {
		var arr = result3[i].gedan_music_id.split(',')
		for (var j = 0; j < arr.length; j++) {
			if (arr[j] == id.toString()) {
				arr.splice(j, 1);
				result3[i].gedan_music_id = arr.join(',');
				narr.push(result3[i]);
			}
		}
	}
	for (var c = 0; c < narr.length; c++) {
		if (narr[c].gedan_music_id == '') {
			await dbQuery('delete from gedan where gedanid=?', [narr[c].gedanid]);
		} else {
			await dbQuery('update gedan set gedan_music_id=? where gedanid=?', [narr[c].gedan_music_id, narr[c].gedanid])
		}
	}
	if (result.affectedRows == 1 && result2.affectedRows >= 0 && result1.affectedRows >= 0) {
		sendSuccess(res, '删除音乐成功!');
	} else {
		sendError(res, 500, '删除音乐失败，请稍后再试!')
	}
}

const getMusic = async function (req, res, next) {
	let sqlStr = 'select music.*,singer.*,musictype.* from music inner join singer on music.singer_id=singer.singerid inner join musictype on music.musictype_id=musictype.musictypeid';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取音乐成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取音乐失败，请稍后再试!')
	}
}

// singerid
const getMusicBySingerId = async function (req, res, next) {
	let {
		singerid
	} = req.query;
	if (!singerid) {
		sendError(res, 200, '歌手不能为空');
		return;
	}

	try {
		await schemaDeleteMusicAndGet.validateAsync({
			id: singerid
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select music.*,singer.* from music inner join singer on music.singer_id=singer.singerid where music.singer_id=?'
	let result = await dbQuery(sqlStr, [singerid]);
	if (result.length >= 0) {
		sendSuccess(res, '获取音乐成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取音乐失败，请稍后再试!')
	}
}

// id
const getMusicById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！')
		return;
	}

	try {
		await schemaGetMusicById.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	var narr = [];
	// 如果id是一串用,分隔的多个
	if (id.indexOf(',') !== -1) {
		let arr = id.split(',');
		for (var i = 0; i < arr.length; i++) {
			let result = await dbQuery('select music.*,singer.* from music inner join singer on music.singer_id = singer.singerid where musicid=?', [arr[i]]);
			narr.push(...result);
		}
		if (narr.length >= 0) {
			sendSuccess(res, '获取音乐成功', {
				data: narr
			})
		} else {
			sendError(res, 500, '获取音乐失败，请稍后重试！');
		}
		// id只是一个
	} else {
		let sqlStr = 'select music.*,singer.* from music inner join singer on music.singer_id = singer.singerid where musicid=?';
		let result = await dbQuery(sqlStr, [id]);
		if (result.length >= 0) {
			sendSuccess(res, '获取音乐成功', {
				data: result
			})
		} else {
			sendError(res, 500, '获取音乐失败，请稍后重试！');
		}
	}
}

// id name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
const editMusic = async function (req, res, next) {
	let info = req.body;

	if (!info.name || !info.musictypeId || !info.singerId || !info.id) {
		sendError(res, 200, '音乐名称或音乐类型或歌手或id不能为空!');
		return;
	}

	try {
		await schemaEditMusic.validateAsync({
			name: info.name,
			musictypeId: info.musictypeId,
			singerId: info.singerId,
			id: info.id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from music where music_name=? and musicid!=?';
	let result = await dbQuery(sqlStr, [info.name, info.id]);
	if (result.length !== 0) {
		sendError(res, 200, '音乐名称被占用，请更换其他音乐名称!');
		return;
	}

	var sqlStr1;
	var result1;
	// musicurl musicfile picfile不一定要改
	if (req.files["picfile"]) {
		let img = req.files["picfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
		if (req.files["musicfile"] && !info.musicurl) {
			let file = req.files["musicfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/')
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_file=?,music_pic_url=?,singer_id=?,music_url=null where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, file, img, info.singerId, info.id]);
		} else if (!req.files["musicfile"] && info.musicurl) {
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_url=?,music_pic_url=?,singer_id=?,music_file=null where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, info.musicurl, img, info.singerId, info.id]);
		} else if (req.files["musicfile"] && info.musicurl) {
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_url=?,music_pic_url=?,singer_id=?,music_file=null where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, info.musicurl, img, info.singerId, info.id]);
		} else if (!req.files["musicfile"] && !info.musicurl) {
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_pic_url=?,singer_id=? where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, img, info.singerId, info.id]);
		}
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改音乐成功!');
		} else {
			sendError(res, 500, '修改音乐失败，请稍后再试!')
		}
	} else {
		if (req.files["musicfile"] && !info.musicurl) {
			let file = req.files["musicfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/')
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_file=?,singer_id=?,music_url=null where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, file, info.singerId, info.id]);
		} else if (!req.files["musicfile"] && info.musicurl) {
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_url=?,singer_id=?,music_file=null where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, info.musicurl, info.singerId, info.id]);
		} else if (req.files["musicfile"] && info.musicurl) {
			sqlStr1 = 'update music set music_name=?,musictype_id=?,music_url=?,singer_id=?,music_file=null where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, info.musicurl, info.singerId, info.id]);
		} else if (!req.files["musicfile"] && !info.musicurl) {
			sqlStr1 = 'update music set music_name=?,musictype_id=?,singer_id=? where musicid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.musictypeId, info.singerId, info.id]);
		}
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改音乐成功!');
		} else {
			sendError(res, 500, '修改音乐失败，请稍后再试!')
		}
	}
}

// musictypeid
const getMusicByMusicTypeId = async function (req, res, next) {
	let {
		musictypeid
	} = req.query;

	if (!musictypeid) {
		sendError(res, 200, '音乐类型不能为空！');
		return;
	}

	try {
		await schemaDeleteMusicAndGet.validateAsync({
			id: musictypeid
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select music.*,singer.*,musictype.* from music inner join singer on music.singer_id=singer.singerid inner join musictype on music.musictype_id=musictype.musictypeid where music.musictype_id=?';
	let result = await dbQuery(sqlStr, [musictypeid]);
	if (result.length >= 0) {
		sendSuccess(res, '获取音乐成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取音乐失败，请稍后再试!')
	}
}


module.exports = {
	addMusicType,
	getMusicByMusicTypeId,
	editMusicType,
	addMusic,
	deleteMusicType,
	getMusicType,
	deleteMusic,
	editMusic,
	getMusic,
	getMusicById,
	getMusicTypeById,
	getMusicBySingerId
}